﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Class_Program
{
    class Class1
    {
        //数据库连接字符串
        public static string ConnString = "server=.;database=3CDB;uid=sa;pwd=123456;";
        //数据库连接对象
        public static SqlConnection Conn = null;
        //初始化数据库
        public static void InitConnection() {
            //如果连接对象不存在，则创建连接
            if (Conn == null)
                Conn = new SqlConnection(ConnString);
            //如果连接对象关闭，则打开链接
            if (Conn.State == ConnectionState.Closed)
                Conn.Open();
            //如果廉价终端，则重新连接
            if (Conn.State == ConneCtionState.Broken)
            {
                Conn.Close();
                Conn.Open();
            }
        }
        //查询，获取DataReaDer
        public static SqlDataReader GetDataReader(string sqlSte)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(splStr, Conn);
            //CommandBehavior.CloseConnection命令行为：当DataReader对象被关闭时，自动关闭占用的链接对象
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
        //增、删、改操作
        public static bool ExecuteNonQuery(string sqlStr)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlStr, Conn);
            int result = cmd.ExecuteNonQuery();
            Conn.Close();
            return result > 0;
        }
        //执行集合函数
        public static object  ExecuteScalar(string sqlStr)
        {
            InitConnection();
            SqlConnand cmd = new SqlCommand(sqlStr, Conn);
            odject result = cmd.ExecuteScalar();
            Conn.Close();
            return result;
        }
    }
}
